package com.xinsmartsky.penmaji.penmaji;

import android.util.Log;

import com.friendlyarm.AndroidSDK.HardwareControler;
import com.xinsmartsky.penmaji.SerialPort.FileOperation;

/**
 * Created by wangxiao on 16-1-14.
 */
public class SerialPortActivity {

    private int devfd;
    private int replysig = 0;//应答信号
    private byte[] receivebuf = new byte[512];
    private byte writecommend;
    private FileOperation fileOperation = new FileOperation();
//    private int new_crc_add = 0;//重新计算的校验和

    public void CommuniProcess(int fd, byte commend) {
        this.writecommend = commend;
        Log.i("fd", "commend是 = " + writecommend);
        /*向下位机发送信号 -- 写数据*/
        /*呼叫信号*/
        devfd = fd;
        int wrt = WriteThread(devfd, (byte) 0x59);//直接截取int中最低一个字节
        if (wrt <= 0) {
            Log.i("fd", "发送呼叫信号#59H失败");
        } else {
            Log.i("fd", "发送呼叫信号#59H成功");
        /*从下位机接收应答信号----读数据*/
            //启动线程
            ReadThread r = new ReadThread();
            r.start();
        }
    }


//    //设置数值 同一时间只能有一个线程修改文件内容 加synchronized
//    public synchronized void SetDataToAddress(int address, byte setdata) {
//        //读文件--> 修改--->发送（发送时从下位机读数据的线程停止？？）
//        Log.i("fd", "开始设置....");
//        byte[] setbytearray = new byte[]{};
//        setbytearray = fileOperation.ReadDataFromFile("serialdatablock.txt");
//        if (setbytearray.length > 0) {
//            int posi = (address - 0x400 + 1);
//            Log.i("fd", "====================下标1======================" + posi);
//            if (address > 0x1000) {
//                posi = (address - 0x400 + 1 - (0x1000 - 0xd00));
//                Log.i("fd", "====================下标======================" + posi);
//            }
//            setbytearray[posi] = setdata;
//            //重新计算校验和
//            for (int index = 0; index < (setbytearray.length - 1); index++) {
//                new_crc_add += setbytearray[index];
//            }
//            setbytearray[setbytearray.length - 1] = (byte) new_crc_add;
//            new_crc_add = 0;
//            //写到文件中
//            fileOperation.WriteDataToFile(setbytearray, "serialdatablock.txt");
////            Log.i("fd", "新的和是:" + Integer.toHexString(setbytearray[setbytearray.length - 1] & 0x000000ff));
//        }
//        Log.i("fd", "设置完成....");
//    }
//
//
//    //设置
//
//    private int zitiaonum = 0;//字条号
//    private int practicelen = 0;//字的实际长度
//    /*写入数组(编辑汉字和图形时)
//    *zitiaonum:字条号;  ArrayLong:汉字数组; practicelen:字条实际长度(字的个数)*/
//    public synchronized void SetArrayToAddress(int type, int num, int[] ArrayLong, int lenth) {
//        zitiaonum = num;
//        practicelen = lenth;
//        switch (type) {
//            //字条 16*16
//            case 1: {
//                SetFile(ArrayLong, 4866, 3328);
//                break;
//            }
//            //图标24*24
//            case 2: {
//                SetFile(ArrayLong, 21762, 512);
//                break;
//            }
//            //图标32*32
//            case 3: {
//                SetFile(ArrayLong, 24322, 512);
//                break;
//            }
//        }
//    }
//
////将数组中的值写入到文件中
//    private void SetFile(int[] ArrayLong, int sindex, int diff) {
//        byte[] setarray = new byte[]{};
//        setarray = fileOperation.ReadDataFromFile("serialdatablock.txt");
//        //起始下标
//        int startindex = sindex + diff * (zitiaonum - 1);//打印出的下标
//        if (setarray.length > 12369) {//=============>总字节数-1
//            for (int i = 0; i < ArrayLong.length; i++) {
//                setarray[startindex + i] = (byte) ArrayLong[i];
//            }
//            setarray[startindex - 1] = (byte) practicelen;
//            //重新计算校验和
//            for (int index = 0; index < (setarray.length - 1); index++) {
//                new_crc_add += setarray[index];
//            }
//            setarray[setarray.length - 1] = (byte) new_crc_add;
//            new_crc_add = 0;
//            //写到文件中
//            fileOperation.WriteDataToFile(setarray, "serialdatablock.txt");
//        }
//
//    }

    byte[] hujiaosingnal = new byte[1];
    byte[] yingdasignal = new byte[512];


//    boolean isWrite = true;

    //发送数据块
    public void SendDataBlock(int fd) {
        int yingdaret = -1;
        int second = 1;
        hujiaosingnal[0] = (byte) 0x59;
        byte[] read_data = new byte[]{};
        read_data = fileOperation.ReadDataFromFile("serialdatablock.txt");
        byte[] read = new byte[]{};
        int hujiaotime = 0;
        int maxtime = 3000;
        while (hujiaotime < maxtime) {
            int wrt = HardwareControler.write(fd, hujiaosingnal);
            if (wrt > 0) {
                if (HardwareControler.select(fd, second, 0) == 1) {
                    yingdaret = HardwareControler.read(fd, yingdasignal, yingdasignal.length);
//                    Log.i("fd", "读到 : " + yingdasignal[0]);
                    if ((yingdaret == 1) && (yingdasignal[0] == (-89))) {
                        if (read_data.length >= 12369) {
                            int send = HardwareControler.write(fd, read_data);
                            if (send > 0) {
                                Log.i("fd", "向串口写数据成功" + fd + "   长度 ：" + send);
                                hujiaotime = maxtime;
                                second = 0;
                            }
                        } else {
                            Log.i("fd", "文件中内容有误");
                        }
                    } else {
//                        Log.i("fd", "读失败" + yingdaret + "///" + yingdasignal[0]);
                    }
                } else {
//                    isWrite = false;
                    Log.i("fd", "超时 ");
                }
            }
            hujiaotime++;
        }
        Log.i("fd", "hujiaotime > 3000");
    }

    /*写数据*/
    public int WriteThread(int devfd, byte commend) {
        byte[] wtebyte = new byte[]{commend};
        int wrt = HardwareControler.write(devfd, wtebyte);
        return wrt;
    }

    /*从下位机读取数据*/
    public class ReadThread extends Thread {
        private boolean flag = true;
        int retSize = 0;

        @Override
        public void run() {
            super.run();
            Log.i("fd", "ReadData start");
            if (HardwareControler.select(devfd, 2, 0) == 1) {
                while ((retSize = HardwareControler.read(devfd, receivebuf, 1)) > 0) {
                    if (retSize == 1) {
                        replysig = (int) receivebuf[0];//收到的应答信号
                        switch (replysig) {
                            //byte的范围 -128~127  0xa7 = -89
                            case (byte) 0xa7: {
                                Log.i("fd", "收到#A7H应答信号");
                            /*收到应答信号 向乙机发送数据 --- 断墨清洗--0xf2  0xec????*/
                                int wrt = WriteThread(devfd, writecommend);
                                if (wrt > 0) {
                                    Log.i("fd", "commend是 -------+" + writecommend);
                                    switch (writecommend) {

                                        case (byte) 0xf2: {
                                            Log.i("fd", "已经发送清洗命令 F2H， 停止读数据");
                                            return;//不读停止线程
                                        }
                                        case (byte) 0xf6: {
                                            Log.i("fd", "已经发送上墨键F6H， 停止读数据");
                                            return;
                                        }
                                        case (byte) 0xec: {
                                            Log.i("fd", "疏通喷嘴，需要2分钟...");
                                            try {
                                                sleep(120000);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            Log.i("fd", "疏通完成， 停止读数据");
                                            return;
                                        }
                                        case (byte) 0x82: {
                                            Log.i("fd", "发送关闭警报成功...");
                                            return;
                                        }
                                        case (byte) 0xf8: {
                                            Log.i("fd", "确定键（返回键），开机系统正在建立压力...需要60s");
                                            break;
                                        }
                                    }
                                } else {
                                    Log.i("fd", "写入命令" + writecommend + "失败");
                                }
                                break;
                            }
                            case 0x15: {
                                Log.i("fd", "下位机不能接收数据");
                                break;
                            }
                            case 0x65: {
                                //乙机收数据等待的时间太长--通信线路有问题
                                Log.i("fd", "下位机等待超时");
                                break;
                            }
                        }
                    } else {
                        //如果读到的是数据块
                    }

                }
            } else {
                Log.i("fd", "超时 (0x0a)");
                return;
            }
        }

        //使线程停止的方法
        public void shutDown() {
            flag = false;
            Log.i("fd", "ReadThread线程停止");
        }
    }


}
